<template>
  <div class="app-container">
    <el-form :model="queryParams" :disabled="loading" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="企业名称" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入企业名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="辖区" prop="xqid">
        <el-cascader :props="props" :placeholder="form.xqname" @change="changeXqidQuery"></el-cascader>
      </el-form-item>
      <el-form-item label="创建人" prop="createrName">
        <el-input
          v-model="queryParams.createrName"
          placeholder="请输入创建人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="操作日期" prop="operTime">
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable>
          <el-option
            v-for="dict in dict.type.check_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:companyrecord:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:companyrecord:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-popover
          placement="bottom"
          width="400"
          trigger="click">
          <div>
            <el-upload
              class="upload-demo"
              drag
              :action="importData"
              :headers="headers"
              :on-success="uploadSuccess"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </div>
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            slot="reference"
            v-hasPermi="['system:companyrecord:import']"
          >导入</el-button>
        </el-popover>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport(1)"
          v-hasPermi="['system:companyrecord:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport(2)"
          v-hasPermi="['system:companyrecord:exportPic']"
        >带图导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          :disabled="!Object.keys(queryParams).length"
          type="success"
          plain
          icon="el-icon-printer"
          size="mini"
          @click="handlePrint"
          v-hasPermi="['system:companyrecord:print']"
        >打印</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="companyrecordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="企业名称" align="center" prop="companyName" />
      <el-table-column label="创建人" align="center" prop="createrName" />
      <el-table-column label="操作人" align="center" prop="operterName" />
      <el-table-column label="检查时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.check_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:companyrecord:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['system:companyrecord:query']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:companyrecord:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改企业检查记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="40">
          <el-col :span="14">
            <el-form-item label="部门" prop="parentName">
              <el-input v-model="form.parentName" disabled placeholder="请输入部门" />
            </el-form-item>
            <el-form-item label="辖区" prop="deptName">
              <el-cascader :props="props" :placeholder="form.deptName" @change="changeXqid"></el-cascader>
            </el-form-item>
            <el-form-item label="企业名称" prop="companyId">
              <el-select
                v-model="form.companyId"
                filterable
                remote
                reserve-keyword
                :placeholder="form.companyName ? form.companyName : '请输入关键字'"
                :remote-method="queryStore"
                :loading="loadingQueryStore"
                @change="changeStore"
              >
                <el-option
                  v-for="item in storeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入地址" />
            </el-form-item>
            <el-form-item label="负责人" prop="fzr">
              <el-input v-model="form.fzr" placeholder="请输入负责人" />
            </el-form-item>
            <el-form-item label="联系方式" prop="phone">
              <el-input v-model="form.fzrPhone" placeholder="请输入联系方式" />
            </el-form-item>
            <el-form-item label="安全人员" prop="safeMember">
              <el-input v-model="form.safeMember" placeholder="请输入负责人" />
            </el-form-item>
            <el-form-item label="联系方式" prop="safePhone">
              <el-input v-model="form.safePhone" placeholder="请输入联系方式" />
            </el-form-item>
            <el-form-item label="企业人数" prop="comNum">
              <el-input v-model="form.comNum" placeholder="请输入地址" />
            </el-form-item>
            <el-form-item label="重点区域" prop="imptArea">
              <el-input v-model="form.imptArea" placeholder="请输入重点区域" />
            </el-form-item>
            <div v-if="getFormStatus === 1">
              <el-form-item label="检查人员签字(合格)" prop="okSign1">
                <div v-if="form.okSign1">
                  <img :src="form.okSign1" style="width: 300px;height: auto;">
                  <el-button type="primary" size="mini" @click="reSign('okSign1')">重签</el-button>
                </div>
                <div v-else>
                  <vue-esign ref="okSign1" style="width: 100%;height: 300px;border: 1px solid #ccc;" :isCrop="isCrop" :lineWidth="lineWidth" :lineColor="lineColor" :bgColor.sync="bgColor" />
                  <el-button type="primary" size="mini" @click="confirmSign('okSign1')">提交</el-button>
                  <el-button type="danger" size="mini" @click="resetSign('okSign1')">重置</el-button>
                </div>
              </el-form-item>
              <el-form-item label="场所人员签字(合格)" prop="okSign2">
                <div v-if="form.okSign2">
                  <img :src="form.okSign2" style="width: 300px;height: auto;">
                  <el-button type="primary" size="mini" @click="reSign('okSign2')">重签</el-button>
                </div>
                <div v-else>
                  <vue-esign ref="okSign2" style="width: 100%;height: 300px;border: 1px solid #ccc;" :isCrop="isCrop" :lineWidth="lineWidth" :lineColor="lineColor" :bgColor.sync="bgColor" />
                  <el-button type="primary" size="mini" @click="confirmSign('okSign2')">提交</el-button>
                  <el-button type="danger" size="mini" @click="resetSign('okSign2')">重置</el-button>
                </div>
              </el-form-item>
              <el-form-item label="主管部门签字(合格)" prop="okSign3">
                <div v-if="form.okSign3">
                  <img :src="form.okSign3" style="width: 300px;height: auto;">
                  <el-button type="primary" size="mini" @click="reSign('okSign3')">重签</el-button>
                </div>
                <div v-else>
                  <vue-esign ref="okSign3" style="width: 100%;height: 300px;border: 1px solid #ccc;" :isCrop="isCrop" :lineWidth="lineWidth" :lineColor="lineColor" :bgColor.sync="bgColor" />
                  <el-button type="primary" size="mini" @click="confirmSign('okSign3')">提交</el-button>
                  <el-button type="danger" size="mini" @click="resetSign('okSign3')">重置</el-button>
                </div>
              </el-form-item>
            </div>
            <div v-if="getFormStatus === 0">
              <el-form-item label="检查人员签字(不合格)" prop="nookSign1">
                <div v-if="form.nookSign1">
                  <img :src="form.nookSign1" style="width: 300px;height: auto;">
                  <el-button type="primary" size="mini" @click="reSign('nookSign1')">重签</el-button>
                </div>
                <div v-else>
                  <vue-esign ref="nookSign1" style="width: 100%;height: 300px;border: 1px solid #ccc;" :isCrop="isCrop" :lineWidth="lineWidth" :lineColor="lineColor" :bgColor.sync="bgColor" />
                  <el-button type="primary" size="mini" @click="confirmSign('nookSign1')">提交</el-button>
                  <el-button type="danger" size="mini" @click="resetSign('nookSign1')">重置</el-button>
                </div>
              </el-form-item>
              <el-form-item label="场所人员签字(不合格)" prop="nookSign2">
                <div v-if="form.nookSign2">
                  <img :src="form.nookSign2" style="width: 300px;height: auto;">
                  <el-button type="primary" size="mini" @click="reSign('nookSign2')">重签</el-button>
                </div>
                <div v-else>
                  <vue-esign ref="nookSign2" style="width: 100%;height: 300px;border: 1px solid #ccc;" :isCrop="isCrop" :lineWidth="lineWidth" :lineColor="lineColor" :bgColor.sync="bgColor" />
                  <el-button type="primary" size="mini" @click="confirmSign('nookSign2')">提交</el-button>
                  <el-button type="danger" size="mini" @click="resetSign('nookSign2')">重置</el-button>
                </div>
              </el-form-item>
              <el-form-item label="主管部门签字(不合格)" prop="nookSign3">
                <div v-if="form.nookSign3">
                  <img :src="form.nookSign3" style="width: 300px;height: auto;">
                  <el-button type="primary" size="mini" @click="reSign('nookSign3')">重签</el-button>
                </div>
                <div v-else>
                  <vue-esign ref="nookSign3" style="width: 100%;height: 300px;border: 1px solid #ccc;" :isCrop="isCrop" :lineWidth="lineWidth" :lineColor="lineColor" :bgColor.sync="bgColor" />
                  <el-button type="primary" size="mini" @click="confirmSign('nookSign3')">提交</el-button>
                  <el-button type="danger" size="mini" @click="resetSign('nookSign3')">重置</el-button>
                </div>
              </el-form-item>
            </div>
            <div v-if="getFormStatus === 2">
              <el-form-item label="检查人员签字(整改)" prop="todoSign1">
                <div v-if="form.todoSign1">
                  <img :src="form.todoSign1" style="width: 300px;height: auto;">
                  <el-button type="primary" size="mini" @click="reSign('todoSign1')">重签</el-button>
                </div>
                <div v-else>
                  <vue-esign ref="todoSign1" style="width: 100%;height: 300px;border: 1px solid #ccc;" :isCrop="isCrop" :lineWidth="lineWidth" :lineColor="lineColor" :bgColor.sync="bgColor" />
                  <el-button type="primary" size="mini" @click="confirmSign('todoSign1')">提交</el-button>
                  <el-button type="danger" size="mini" @click="resetSign('todoSign1')">重置</el-button>
                </div>
              </el-form-item>
              <el-form-item label="场所人员签字(整改)" prop="todoSign2">
                <div v-if="form.todoSign2">
                  <img :src="form.todoSign2" style="width: 300px;height: auto;">
                  <el-button type="primary" size="mini" @click="reSign('todoSign2')">重签</el-button>
                </div>
                <div v-else>
                  <vue-esign ref="todoSign2" style="width: 100%;height: 300px;border: 1px solid #ccc;" :isCrop="isCrop" :lineWidth="lineWidth" :lineColor="lineColor" :bgColor.sync="bgColor" />
                  <el-button type="primary" size="mini" @click="confirmSign('todoSign2')">提交</el-button>
                  <el-button type="danger" size="mini" @click="resetSign('todoSign2')">重置</el-button>
                </div>
              </el-form-item>
              <el-form-item label="主管部门签字(整改)" prop="todoSign3">
                <div v-if="form.todoSign3">
                  <img :src="form.todoSign3" style="width: 300px;height: auto;">
                  <el-button type="primary" size="mini" @click="reSign('todoSign3')">重签</el-button>
                </div>
                <div v-else>
                  <vue-esign ref="todoSign3" style="width: 100%;height: 300px;border: 1px solid #ccc;" :isCrop="isCrop" :lineWidth="lineWidth" :lineColor="lineColor" :bgColor.sync="bgColor" />
                  <el-button type="primary" size="mini" @click="confirmSign('todoSign3')">提交</el-button>
                  <el-button type="danger" size="mini" @click="resetSign('todoSign3')">重置</el-button>
                </div>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="10">
            <el-row v-if="!form.recorddtlList.length">
              <el-col :span="20">
                <div style="color: #fff;">1</div>
              </el-col>
              <el-col :span="4">
                <el-button type="success" icon="el-icon-plus" circle @click="addCheckItem"></el-button>
              </el-col>
            </el-row>
            <el-row v-for="(item, index) in form.recorddtlList" :key="index" :gutter="20" style="padding: 10px 0;border-top: 1px solid #ccc;">
              <el-col :span="20">
                <el-form-item label="隐患类别" prop="checkinfoid">
                  <el-select v-model="item.typeId" clearable>
                    <el-option
                      v-for="(info, index) in dangerList"
                      :key="info.value"
                      :label="info.label"
                      :value="info.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="隐患描述" prop="dangerInfo">
                  <el-input v-model="item.dangerInfo" placeholder="请输隐患描述" />
                </el-form-item>
                <el-form-item label="所属部门" prop="deptType">
                  <el-input v-model="item.deptType" placeholder="请输入所属部门" />
                </el-form-item>
                <el-form-item label="检查内容" prop="companyContent">
                  <el-input v-model="item.companyContent" placeholder="请输入检查内容" />
                </el-form-item>
                <el-form-item label="是否合格" prop="isOk">
                  <el-switch
                    v-model="item.isOk"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="1"
                    :inactive-value="0">
                  </el-switch>
                </el-form-item>
                <el-form-item v-if="item.isOk === 0" label="隐患照片" prop="checkPhotos">
                  <el-upload
                    :action="uploadUrl"
                    :file-list="item.checkPhotos"
                    list-type="picture-card"
                    class="upload"
                    :on-success="(res, file, fileList) => uploadImgSuccess(res, file, fileList, 'checkPhotos', item)"
                    :before-upload="file => uploadBefore(file, 'checkPhotos')"
                    :before-remove="delPhoto"
                  >
                    <i class="el-icon-plus"></i>
                  </el-upload>
                </el-form-item>
                <el-form-item v-if="item.recordId && item.isOk === 0" label="整改建议" prop="content">
                  <el-input v-model="item.zgjy" placeholder="请输入整改建议" />
                </el-form-item>
                <el-form-item v-if="item.recordId && item.isOk === 0" label="整改照片" prop="rectifyPhotos">
                  <el-upload
                    :action="uploadUrl"
                    :file-list="item.rectifyPhotos"
                    list-type="picture-card"
                    class="upload"
                    :on-success="(res, file, fileList) => uploadImgSuccess(res, file, fileList, 'rectifyPhotos', item)"
                    :before-upload="file => uploadBefore(file, 'rectifyPhotos')"
                    :before-remove="delPhoto"
                  >
                    <i class="el-icon-plus"></i>
                  </el-upload>
                </el-form-item>
                <el-form-item v-if="item.recordId && item.isOk === 0" label="是否合格" prop="status">
                  <el-switch
                    v-model="item.status"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="1"
                    :inactive-value="0">
                  </el-switch>
                </el-form-item>
              </el-col>
              <el-col :span="4" class="item-btn">
                <el-button v-if="index === form.recorddtlList.length - 1" type="success" icon="el-icon-plus" circle @click="addCheckItem"></el-button>
                <el-button v-if="form.recorddtlList.length > 0" type="danger" icon="el-icon-minus" circle @click="minusCheckItem(index)"></el-button>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="openDetail" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="40">
          <el-col :span="10">
            <el-form-item label="企业名称" prop="companyName">
              {{ form.companyName }}
            </el-form-item>
            <el-form-item label="检查日期" prop="createTime">
              {{ form.createTime }}
            </el-form-item>
            <el-form-item label="创建人" prop="creater">
              {{ form.createrName }}
            </el-form-item>
            <el-form-item v-if="form.operterName" label="操作人" prop="operter">
              {{ form.operterName }}
            </el-form-item>
            <el-form-item v-if="form.operTime" label="操作时间" prop="operTime">
              {{ form.operTime }}
            </el-form-item>
            <el-form-item v-if="form.okSign1 && form.status === 1" label="检查人员签字（合格）" prop="okSign1">
              <img :src="form.okSign1" style="width: 300px;height: auto;">
            </el-form-item>
            <el-form-item v-if="form.okSign2 && form.status === 1" label="场所人员签字(合格)" prop="okSign2">
              <img :src="form.okSign2" style="width: 300px;height: auto;">
            </el-form-item>
            <el-form-item v-if="form.okSign3 && form.status === 1" label="主管部门签字(合格)" prop="okSign3">
              <img :src="form.okSign3" style="width: 300px;height: auto;">
            </el-form-item>
            <el-form-item v-if="form.nookSign1 && form.status === 2" label="检查人员签字(不合格)" prop="nookSign1">
              <img :src="form.nookSign1" style="width: 300px;height: auto;">
            </el-form-item>
            <el-form-item v-if="form.nookSign2 && form.status === 2" label="场所人员签字(不合格)" prop="nookSign2">
              <img :src="form.nookSign2" style="width: 300px;height: auto;">
            </el-form-item>
            <el-form-item v-if="form.nookSign3 && form.status === 2" label="主管部门签字(不合格)" prop="nookSign3">
              <img :src="form.nookSign3" style="width: 300px;height: auto;">
            </el-form-item>
            <el-form-item v-if="form.todoSign1 && form.status === 0" label="检查人员签字(整改)" prop="todoSign1">
              <img :src="form.todoSign1" style="width: 300px;height: auto;">
            </el-form-item>
            <el-form-item v-if="form.todoSign2 && form.status === 0" label="场所人员签字(整改)" prop="todoSign2">
              <img :src="form.todoSign2" style="width: 300px;height: auto;">
            </el-form-item>
            <el-form-item v-if="form.todoSign3 && form.status === 0" label="主管部门签字(整改)" prop="todoSign3">
              <img :src="form.todoSign3" style="width: 300px;height: auto;">
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <div v-for="(item, index) in form.recorddtlList" :key="item.id" style="padding: 10px 0; border-bottom: 1px solid #bbb;">
              <el-form-item label="隐患类别">
                {{ item.typeName }}
              </el-form-item>
              <el-form-item label="隐患内容">
                {{ item.dangerInfo }}
              </el-form-item>
              <el-form-item label="所属部门">
                {{ item.deptType }}
              </el-form-item>
              <el-form-item v-if="!!item.companyContent" label="检查内容">
                <dict-tag :options="dict.type.check_status" :value="item.isOk" style="display: inline-block;"/> {{ item.companyContent }}
              </el-form-item>
              <el-form-item v-if="item.checkPhotos && item.checkPhotos.length" label="检查照片">
                <span v-for="(img, i) in item.checkPhotos" :key="i">
                  <el-image
                    style="width: 100px; height: 100px"
                    :src="img.url"
                    :preview-src-list="item.checkPhotos.map(p => p.url)">
                  </el-image>
                </span>
              </el-form-item>
              <el-form-item v-if="!!item.content" label="整改建议" prop="content">
                {{ item.content }}
              </el-form-item>
              <el-form-item v-if="!!item.zgjy && item.isOk === 0" label="整改建议" prop="content">
                {{ item.zgjy }}
              </el-form-item>
              <el-form-item v-if="item.rectifyPhotos && item.rectifyPhotos.length" label="整改照片">
                <span v-for="(img, i) in item.rectifyPhotos" :key="i">
                  <el-image
                    style="width: 100px; height: 100px"
                    :src="img.url"
                    :preview-src-list="item.rectifyPhotos.map(p => p.url)">
                  </el-image>
                </span>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="openDetail = false">确 定</el-button>
        <el-button @click="openDetail = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCompanyrecord, getCompanyrecord, delCompanyrecord, addCompanyrecord, updateCompanyrecord, importData } from "@/api/system/companyrecord";
import { listCompany } from '@/api/system/company'
import { listDanger } from '@/api/system/danger'
import vueEsign from 'vue-esign'
import {uploadUrl, uploadFile} from "@/api/system/config";
import { base64ToImg, formatDate1 } from '@/utils'
import { mapGetters } from 'vuex'
import { getdeptByparentid } from '@/api/system/dept'
import { delphoto, getRecord } from '@/api/system/record'
import store from "@/store";
import {getToken} from '@/utils/auth'
export default {
  name: "Companyrecord",
  dicts: ['sys_normal_disable', 'check_status', 'store_type', 'store_status'],
  components: {
    vueEsign
  },
  data() {
    return {
      importData,
      uploadUrl,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企业检查记录表格数据
      companyrecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openDetail: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyId: null,
        creater: null,
        operter: null,
        operTime: null,
        status: null,
        okSign1: null,
        okSign2: null,
        okSign3: null,
        nookSign1: null,
        nookSign2: null,
        nookSign3: null,
        todoSign1: null,
        todoSign2: null,
        todoSign3: null
      },
      date: [],
      // 表单参数
      form: {
        recorddtlList: []
      },
      // 表单校验
      rules: {
        companyId: [
          { required: true, message: "企业ID不能为空", trigger: "blur" }
        ],
      },
      lineWidth: 6,
      lineColor: '#000000',
      bgColor: '',
      resultImg: '',
      isCrop: false,
      getFormStatus: 1,
      props: {
        checkStrictly: true,
        lazy: true,
        lazyLoad (node, resolve) {
          const params = {
            parentid: ['admin', 'adm'].filter(item => store.getters.roles.includes(item)).length ? 200 : store.getters.deptId,
            deptType: '0'
          }
          console.log('node', node)
          params.parentid = node.value || (['admin', 'adm'].filter(item => store.getters.roles.includes(item)).length ? 200 : store.getters.deptId)
          const { level } = node;
          getdeptByparentid(params).then(res => {
            const nodes = res.data.map(item => {
              return {
                value: item.deptId,
                label: item.deptName,
                leaf: level >= 1
              }
            })
            resolve(nodes)
          })
        }
      },
      loadingQueryStore: false,
      storeList: [],
      storesData: [],
      dangerList: [],
      headers: {
        Authorization: 'Bearer ' + getToken()
      }
    };
  },
  created() {
    this.getList();
  },
  computed: {
    ...mapGetters([
      'deptId',
      'deptName'
    ]),
    envType() {
      return process.env.VUE_APP_TYPE
    }
  },
  watch: {
    'form.recorddtlList': {
      handler: function(nv, ov) {
        console.log(nv, ov)
        if (!nv.length || (nv.length && nv.every(item => item.recordId && item.status === 1))) {
          this.getFormStatus = 1
          this.form.status = 1
          return
        }
        if (nv.length && nv.some(item => item.recordId && item.status === 0)) {
          this.getFormStatus = 0
          this.form.status = 0
          return
        }
        this.getFormStatus = 2
        this.form.status = 2
        console.log('status', this.getFormStatus)
      },
      deep: true
    },
    'date': {
      handler: function(nv, ov) {
        console.log('date nv ov', nv, ov)
        if (nv && nv.length === 2) {
          // 正常选择日期范围
          this.queryParams.beginDate = formatDate1(nv[0]);
          this.queryParams.endDate = formatDate1(nv[1]);
        } else {
          // 清除日期范围
          this.queryParams.beginDate = '';
          this.queryParams.endDate = '';
        }
      }
    }
  },
  methods: {
    /** 查询企业检查记录列表 */
    getList() {
      this.loading = true;
      listCompanyrecord(this.queryParams).then(response => {
        this.companyrecordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    changeXqid(v) {
      this.form.deptId = v[v.length - 1]
      console.log('v', v, this.form.deptId)
    },
    changeXqidQuery(v) {
      this.queryParams.pdeptId = v[v.length - 1]
    },
    queryStore(v) {
      console.log('vvv', v)
      const params = {
        name: v,
        pageNum: 1,
        pageSize: 10000
      }
      this.loadingQueryStore = true
      listCompany(params).then(res => {
        this.storesData = res.rows
        this.storeList = res.rows.map(item => {
          return {
            value: item.id,
            label: `${item.name} - ${item.fzr} - ${item.address}`
          }
        })
        this.loadingQueryStore = false
      })
    },
    changeStore(v) {
      console.log('vvvv', v)
      const arr = this.storesData.map(item => item.id)
      const index = arr.indexOf(v)
      console.log('vvvv', v, this.storeList, arr, index)

      this.form.address = this.storesData[index].address
      this.form.fzr = this.storesData[index].fzr
      this.form.fzrPhone = this.storesData[index].fzrPhone
      this.form.safeMember = this.storesData[index].safeMember
      this.form.safePhone = this.storesData[index].safePhone
      this.form.comNum = this.storesData[index].comNum
      this.form.companyId = this.storesData[index].id
      this.form.companyName = this.storesData[index].name
      this.form.imptArea = this.storesData[index].imptArea
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        recorddtlList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // 清空日期范围变量
      this.date = []; 
      this.resetForm("queryForm");
      this.handleQuery();
    },
    addCheckItem() {
      this.form.recorddtlList = [
        ...this.form.recorddtlList,
        ...[
          {
            typeId: '',
            dangerInfo: '',
            deptType: '',
            checkPhotos: [],
            content: '',
            rectifyPhotos: [],
            status: 1
          }
        ]
      ]
    },
    minusCheckItem(index){
      this.form.recorddtlList.splice(index, 1)
    },
    uploadBefore(file, type) {
      console.log('file', file)
      const isJPG = ['image/jpeg', 'image/png'].includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 5;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG,PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 5MB!');
      }
      return isJPG && isLt2M;
    },
    uploadImgSuccess(res, file, fileList, type, item) {
      console.log('res', res, file, fileList)
      let typeTmp
      switch (type) {
        case 'checkPhotos':
          typeTmp = 3
          break
        case 'rectifyPhotos':
          typeTmp = 4
          break
        default:
      }
      item[type] = [
        ...item[type],
        ...[
          {
            type: typeTmp,
            url: res.fileName,
            imgUrl: res.fileName
          }
        ]
      ]
    },
    confirmSign(type) {
      this.$refs[type].generate().then(res => {
        console.log('reeeeeeee', res)
        const file = base64ToImg(res, type)
        const formData = new FormData()
        formData.append('file', file)
        uploadFile(formData).then(res => {
          console.log('res', res)
          // this.form[type] = res.fileName
          this.$set(this.form, type, res.fileName)
        })
      }).catch(err => {
        alert(err) // 画布没有签字时会执行这里 'Not Signned'
      })
    },
    resetSign(type) {
      this.$refs[type].reset()
    },
    reSign(type) {
      this.form[type] = ''
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加企业检查记录";
      this.form.parentId = this.deptId
      this.form.parentName = this.deptName
      listDanger().then(res => {
        this.dangerList = res.rows.map(item => {
          return {
            label: item.name,
            value: item.id
          }
        })
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      listDanger().then(res => {
        this.dangerList = res.rows.map(item => {
          return {
            label: item.name,
            value: item.id
          }
        })
        const id = row.id || this.ids
        getCompanyrecord(id).then(response => {
          this.form = response.data;
          for(const record of this.form.recorddtlList) {
            if (record.photoList.length) {
              record.checkPhotos = []
              record.rectifyPhotos = []
              for(const img of record.photoList) {
                if (img.type === 3) {
                  record.checkPhotos = [
                    ...record.checkPhotos,
                    ...[
                      {
                        id: img.id,
                        name: img.id,
                        url: img.imgUrl
                      }
                    ]
                  ]
                }
                if (img.type === 4) {
                  record.rectifyPhotos = [
                    ...record.rectifyPhotos,
                    ...[
                      {
                        id: img.id,
                        name: img.id,
                        url: img.imgUrl
                      }
                    ]
                  ]
                }
              }
            }
          }
          this.open = true;
          this.title = "修改企业检查记录";
        });
      })
    },
    handleDetail(row) {
      const id = row.id || this.ids
      getCompanyrecord(id).then(response => {
        this.form = response.data;
        for(const record of this.form.recorddtlList) {
          if (record.photoList.length) {
            record.checkPhotos = []
            record.rectifyPhotos = []
            for(const img of record.photoList) {
              if (img.type === 3) {
                record.checkPhotos = [
                  ...record.checkPhotos,
                  ...[
                    {
                      id: img.id,
                      name: img.id,
                      url: img.imgUrl
                    }
                  ]
                ]
              }
              if (img.type === 4) {
                record.rectifyPhotos = [
                  ...record.rectifyPhotos,
                  ...[
                    {
                      id: img.id,
                      name: img.id,
                      url: img.imgUrl
                    }
                  ]
                ]
              }
            }
          }
        }
        this.openDetail = true
        this.title = '查看记录'
      })
    },
    delPhoto (file, fileList) {
      console.log('file', file)
      if (!file.id) return
      const params = {
        id: file.id
      }
      delphoto(params)
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          for (let i = 0; i < this.form.recorddtlList.length; i++) {
            this.form.recorddtlList[i].photoList = []
            this.form.recorddtlList[i].photoList = [
              ...this.form.recorddtlList[i].checkPhotos || [],
              ...this.form.recorddtlList[i].rectifyPhotos || []
            ]
          }
          if (this.form.id != null) {
            updateCompanyrecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCompanyrecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handlePrint() {
      console.log('this.queryData', this.queryParams)
      this.$router.push({
        path: '/company/print-data',
        query: this.queryParams
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除企业检查记录编号为"' + ids + '"的数据项？').then(function() {
        return delCompanyrecord(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    uploadSuccess(res, file, fileList) {
      console.log('upres', res, file, fileList)
      this.$message({
        message: res.code === 200 ? '导入成功！' : res.msg,
        type: res.code === 200 ? 'success' : 'error'
      })
      this.getList()
    },
    /** 导出按钮操作 */
    handleExport(type) {
      this.download('/system/companyrecord/export?exportType=' + type, {
        ...this.queryParams
      }, `companyrecord_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
.upload .el-upload--picture-card{width: 60px;height: 60px;line-height: 58px;}
.upload .el-upload-list--picture-card .el-upload-list__item{width: 60px;height: 60px;line-height: 58px;}
</style>
<style scoped>
.item-btn button{margin: 0;margin-bottom: 10px;}
</style>
